package com.woniu.zsd.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.Key;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

@Component
public class JWTUtil {
    @Resource
    private  StringRedisTemplate stringRedisTemplate;
    //自定义的秘钥
    //HS256：即字节长度>=32
    static String sect ="yjfasfdasdfadsfwfrasdfsadffcasijfasadfasfdlkfjlasjflksajfd";
    //生成token
    //键值对包含用户信息
    //以分钟为单位的时间 代表jwt的有效时间
    public  String createToken(Map<String, Object> body, Integer mil) {
        Key key = Keys.hmacShaKeyFor(sect.getBytes());
        return Jwts.builder()
                .setClaims(body)
                .setExpiration(new Date(System.currentTimeMillis() + mil * 60 * 1000))
                .signWith(key)
                .compact();
    }
    //解析token
    public  Claims parseToken(String token) {
        Key key = Keys.hmacShaKeyFor(sect.getBytes());
        return Jwts.parserBuilder().setSigningKey(key)
                .build().parseClaimsJws(token).getBody();
    }

    //获取accountId
    public  Integer getAccountId(String token) throws Exception{
        String accessToken = stringRedisTemplate.opsForValue().get(RedisKey.ACCESS_REFRESH_TOKEN2(token));
        Claims claims = parseToken(accessToken);
        Integer accountId = Integer.valueOf(claims.get("accountId").toString());
        return accountId;
    }
    //获取userId
    public  Integer getUserId(String token) throws Exception{
        String refreshToken = stringRedisTemplate.opsForValue().get(RedisKey.userRefreshToken(token));

        return Integer.parseInt(parseToken(refreshToken).get("userId").toString());
//        return Integer.parseInt(Objects.requireNonNull(stringRedisTemplate.opsForValue().get(RedisKey.userAccessTokenExpireTime(accessToken))));
    }


}
